package com.cn.zkc3;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenyuncong on 2019/4/1.
 */
public class TastChild2 {
    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient=new ZkClient(new ZkConnection(TastAssist.connectString,10000));

        String masterNode="/task-assist";
        String nodeName="/task-1";
        String child=masterNode+nodeName;
        String checkNode=masterNode+"/check-node";

        zkClient.subscribeChildChanges(masterNode, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChild) throws Exception {
                System.out.println("--------------监听主节点 和 子节点 变化---------------");
                System.out.println("parentPath=" + parentPath);
                System.out.println("currentChild=" + currentChild);
            }

        });

        zkClient.subscribeChildChanges(child, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChild) throws Exception {
                System.out.println("--------------监听 子节点 变化---------------");
                System.out.println("parentPath=" + parentPath);
                System.out.println("currentChild=" + currentChild);
            }

        });

        //监控主节 修改数据，和删除(subscribeChildChanges先运行然后再到subscribeDataChanges监听)
        zkClient.subscribeDataChanges(child, new IZkDataListener() {
            //主节点数据修改
            @Override
            public void handleDataChange(String path, Object data) throws Exception {
                System.out.println("修改节点 path=" + path + ", value=" + data);
            }

            //主节点删除
            @Override
            public void handleDataDeleted(String path) throws Exception {
                System.out.println("删除的节点 path" + path);
            }
        });
        Map<String,Object> map = new HashMap<>();
        Tast tast = null;
        boolean bool = zkClient.exists(child);
        if(!bool){
            tast=new Tast(0,nodeName);
            zkClient.createEphemeral(child,tast);
        }

        Thread.sleep(1000);

        tast=new Tast(1,nodeName);
        zkClient.writeData(child,tast);

        Thread.sleep(1000);

        while (true){
            Thread.sleep(3000);
            boolean checkBool = zkClient.exists(checkNode);
            if(!checkBool){
                zkClient.createPersistent(checkNode,child);
            }else{
                zkClient.writeData(checkNode,child);
            }
        }


    }
}
